
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

import java.util.*;
import java.io.*;

public class MainFrame extends JFrame implements MouseListener, ActionListener,WindowListener, ChangeListener {


	/**
	 * 
	 */
	private static final long serialVersionUID = -4703097630895940473L;

	static MainFrame instance;
	
	JTabbedPane tabPan;
	DetailSideBar details;
	java.util.List<PolicyFrame> policies;
	/*******right click tab*********/
	JPopupMenu pMenuTab;
	JMenuItem closeTab;
	JMenuItem saveTab;
	JMenuItem newTab;
	/********menu bar***************/
	JMenuBar menuBar;
	JMenu fileMenu, dataGroupMenu,helpMenu;
	JMenuItem newMenu, openMenu, saveMenu, saveAsMenu,/**/ generateMenu, /**/getFromWebMenu,getFromXmlMenu,/**/ closeMenu, exitMenu;
	JMenuItem newGroup, groupInfo,deleteGroup;
	JMenuItem help,info;
	
	/**********for save file********/
	int newFileCnt;
	JFileChooser filechooserProj;
	JFileChooser filechooserXml;
	/**********for close window*****/
	JDialog closeWindow;
	JButton closeStay;
	JButton closeClose;
	/**********for close current project*****/
	JDialog fileNotSaved;
	JButton fileNotSavedYes;
	JButton fileNotSavedNo;
	JButton fileNotSavedCancel;
	
	/********* for editing data group properties ***********/
	JDialog dataGroupProperty;
	JButton dataGroupOk;
	JButton dataGroupCancel;
	JTextField dataGroupName;
	JRadioButton currentRequest;
	JRadioButton statedPurpose;
	JRadioButton applicableLaw;
	JRadioButton businessPractice;
	JRadioButton indefinite;
	JTextArea dataGroupDescription;
	JCheckBox dataGroupIdentifiable;
	int dataGroupModify;
	
	/********* for warning of group name missing ***********/
	JDialog groupNameMissing;
	JButton groupNameMissingOk;
	
	public static void main(String args[]){
		MainFrame.getInstance().config();
		MainFrame.getInstance().setVisible(true);
	}
	
	public static MainFrame getInstance(){
		if(instance==null)
			instance=new MainFrame();
		return instance;
	}
	
	private MainFrame(){
		super("P3P Editor");
		policies=new ArrayList<PolicyFrame>();
		
		newFileCnt=1;
		dataGroupModify=-1;
	}
	public void config(){
		PolicyFrame pf=new PolicyFrame();

		pf.config();
		
		policies.add(pf);
		
		tabPan=new JTabbedPane();
		tabPan.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
		
		tabPan.add("new project "+newFileCnt,pf.tab);
		newFileCnt++;
		
		/***************right click on tab****************/
		pMenuTab = new JPopupMenu();
		newTab = new JMenuItem("new project");
		pMenuTab.add(newTab);
		saveTab = new JMenuItem("save project");
		pMenuTab.add(saveTab);
		closeTab = new JMenuItem("close");
		pMenuTab.add(closeTab);
		
		/************** menu *****************************/
		menuBar = new JMenuBar();
		fileMenu=new JMenu("File");
		dataGroupMenu=new JMenu("Data Group");
		helpMenu=new JMenu("Help");
		
		newMenu = new JMenuItem("New project");
		openMenu = new JMenuItem("Open existing project");
		saveMenu = new JMenuItem("Save current project");
		saveAsMenu = new JMenuItem("Save current Project as...");
		generateMenu = new JMenuItem("Generate P3P file");
		getFromWebMenu = new JMenuItem("Analyze P3P policy from web");
		getFromXmlMenu  = new JMenuItem("Analyze P3P policy from file");
		closeMenu = new JMenuItem("Close current project");
		exitMenu = new JMenuItem("Exit");
		newGroup = new JMenuItem("Create a new data group");
		groupInfo = new JMenuItem("Modify Group properties");
		groupInfo.setEnabled(false);
		deleteGroup = new JMenuItem("Delete data group");
		deleteGroup.setEnabled(false);
		help = new JMenuItem("Help");
		info = new JMenuItem("About");
		
		newMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,2));
		openMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,2));
		saveMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,2));
		saveAsMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,3));
		closeMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,2));
		exitMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,3));
		
		fileMenu.add(newMenu);
		fileMenu.add(openMenu);
		fileMenu.add(saveMenu);
		fileMenu.add(saveAsMenu);
		fileMenu.add(closeMenu);
		fileMenu.add(new JSeparator());
		fileMenu.add(generateMenu);
		fileMenu.add(new JSeparator());
		fileMenu.add(getFromWebMenu);
		fileMenu.add(getFromXmlMenu);
		fileMenu.add(new JSeparator());
		fileMenu.add(exitMenu);
		
		dataGroupMenu.add(newGroup);
		dataGroupMenu.add(groupInfo);
		dataGroupMenu.add(deleteGroup);
		
		helpMenu.add(help);
		helpMenu.add(info);
		
		menuBar.add(fileMenu);
		menuBar.add(dataGroupMenu);
		menuBar.add(helpMenu);
		this.setJMenuBar(menuBar);
		
		/**************file chooser***********************/
		filechooserProj=new JFileChooser();
		filechooserProj.setAcceptAllFileFilterUsed(false);
		filechooserProj.addChoosableFileFilter(new FileFilterbyName("p3pproj"));
		
		filechooserXml=new JFileChooser();
		filechooserXml.setAcceptAllFileFilterUsed(false);
		filechooserXml.addChoosableFileFilter(new FileFilterbyName("xml"));
		/**************ADD LISTENER***********************/
		newTab.addActionListener(this);
		saveTab.addActionListener(this);
		closeTab.addActionListener(this);
		
		newMenu.addActionListener(this);
		openMenu.addActionListener(this);
		saveMenu.addActionListener(this);
		saveAsMenu.addActionListener(this);
		generateMenu.addActionListener(this);
		getFromWebMenu.addActionListener(this);
		getFromXmlMenu.addActionListener(this);
		closeMenu.addActionListener(this);
		exitMenu.addActionListener(this);
		
		newGroup.addActionListener(this);
		groupInfo.addActionListener(this);
		deleteGroup.addActionListener(this);
		
		help.addActionListener(this);
		info.addActionListener(this);
		
		/***********SET SIZE AND LOCATION****************/
	  	setLayout(new BorderLayout());
	  	getContentPane().add(tabPan,"West");
	  	details=new DetailSideBar();
	  	getContentPane().add(details,"Center");
	  	Toolkit toolkit = Toolkit.getDefaultToolkit();
		Dimension d=toolkit.getScreenSize();
		setSize(1024,720);
		setLocation((d.width-1024)/2,(d.height-720)/4);
		setResizable(false);
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		addWindowListener(this);
		
		/************close window dialog****************/
		closeWindow=new JDialog(this,"Warning");
		closeStay=new JButton("OK");
		closeClose=new JButton("Exit anyway");
		closeStay.addActionListener(this);
		closeClose.addActionListener(this);
		JLabel closeWarn=new JLabel("<html> <body>&nbsp &nbsp &nbsp &nbsp You have unsaved work<br>do you want to go back to work?<br></body></html>");
		closeWindow.setSize(240,110);
		closeWindow.setResizable(false);
		closeWindow.setLocation((d.width-240)/2,(d.height-110)/2);
		JPanel cw1 = new JPanel(new FlowLayout(FlowLayout.CENTER));
		cw1.add(closeStay);
		cw1.add(closeClose);
		JPanel cw2 = new JPanel(new BorderLayout());
		cw2.add(closeWarn,"North");
		cw2.add(cw1,"Center");
		closeWindow.setLayout(new FlowLayout(FlowLayout.CENTER));
		closeWindow.add(cw2);
		
		/************close project dialog****************/
		fileNotSaved=new JDialog(this,"Warning");
		fileNotSavedYes=new JButton("Yes");
		fileNotSavedNo=new JButton("No");
		fileNotSavedCancel=new JButton("Cancel");
		fileNotSavedYes.addActionListener(this);
		fileNotSavedNo.addActionListener(this);
		fileNotSavedCancel.addActionListener(this);
		JLabel fileNotSavedWarn=new JLabel("<html><body> The project you are closing is not saved <br>do you want to save it before closing?<br></body></html>");
		fileNotSaved.setSize(300,110);
		fileNotSaved.setResizable(false);
		fileNotSaved.setLocation((d.width-300)/2,(d.height-110)/2);
		JPanel fns = new JPanel(new FlowLayout(FlowLayout.CENTER));
		fns.add(fileNotSavedYes);
		fns.add(fileNotSavedNo);
		fns.add(fileNotSavedCancel);
		JPanel fns2 = new JPanel(new BorderLayout());
		fns2.add(fileNotSavedWarn,"North");
		fns2.add(fns,"Center");
		fileNotSaved.setLayout(new FlowLayout(FlowLayout.CENTER));
		fileNotSaved.add(fns2);
		
		/************dialog for setting data group properties***************/
		dataGroupProperty = new JDialog(this,"Data Group Property");
		dataGroupProperty.setSize(480,480);
		dataGroupProperty.setResizable(false);
		
		dataGroupOk = new JButton("Ok");
		dataGroupCancel = new JButton("Cancel");
		dataGroupOk.addActionListener(this);
		dataGroupCancel.addActionListener(this);
		
		dataGroupName = new JTextField(30);
		currentRequest =new JRadioButton("For the current request or session only");
		statedPurpose =new JRadioButton("For the stated collection purposes only *");
		applicableLaw =new JRadioButton("As required by applicable law *");
		businessPractice =new JRadioButton("As determined by our business practices *");
		indefinite =new JRadioButton("Indefinitely");
		ButtonGroup buttonGroup=new ButtonGroup();
		buttonGroup.add(currentRequest);
		buttonGroup.add(statedPurpose);
		buttonGroup.add(applicableLaw);
		buttonGroup.add(businessPractice);
		buttonGroup.add(indefinite);
		indefinite.setSelected(true);
		dataGroupDescription= new JTextArea(6,30);
		dataGroupDescription.setLineWrap(true);
		JScrollPane sp=new JScrollPane(dataGroupDescription);
		sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		dataGroupIdentifiable = new JCheckBox("Data in this group cannot be linked to the visitor's identity");
		
		JLabel groupName=new JLabel("Group Name");
		JLabel groupDescription=new JLabel("<html><body><br>Explaination of why the data is requested</body></html>");
		JLabel groupRetention = new JLabel("<html><body><br>Specify how long the data will be kept</body></html>");
		JLabel groupRententionEx = new JLabel("<html><body>* For these choices, your hunam-readable privacy policy must<br> &nbsp &nbsp give a more complete explaination of the retention policy<br><br></body></html>");
		
		JPanel p1=new JPanel(new FlowLayout(FlowLayout.LEFT));
		p1.add(groupName);
		p1.add(dataGroupName);
		
		JPanel p2_1=new JPanel(new GridLayout(5,1));
		p2_1.add(currentRequest);
		p2_1.add(statedPurpose);
		p2_1.add(applicableLaw);
		p2_1.add(businessPractice);
		p2_1.add(indefinite);
		JPanel p2=new JPanel(new FlowLayout(FlowLayout.CENTER));
		p2.add(p2_1);
		JPanel p3=new JPanel(new BorderLayout());
		JPanel p4=new JPanel(new BorderLayout());
		JPanel p5=new JPanel(new BorderLayout());
		JPanel p6=new JPanel(new BorderLayout());
		JPanel p7=new JPanel(new BorderLayout());
		JPanel p8=new JPanel(new BorderLayout());
		p3.add(p1,"North");
		p3.add(groupDescription,"Center");
		p4.add(p3,"North");
		p4.add(sp,"Center");
		p5.add(p4,"North");
		p5.add(groupRetention,"Center");
		p6.add(p5,"North");
		p6.add(p2,"Center");
		p7.add(p6,"North");
		p7.add(groupRententionEx,"Center");
		p8.add(p7,"North");
		p8.add(dataGroupIdentifiable,"Center");
		JPanel p9=new JPanel(new FlowLayout(FlowLayout.CENTER));
		p9.add(p8);
		dataGroupProperty.setLayout(new BorderLayout());
		dataGroupProperty.add(p9,"Center");
		JPanel p10=new JPanel(new FlowLayout(FlowLayout.RIGHT));
		p10.add(dataGroupOk);
		p10.add(dataGroupCancel);
		dataGroupProperty.add(p10,"South");
		dataGroupProperty.setLocation((d.width-480)/2,(d.height-480)/2);
		
		dataGroupProperty.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		dataGroupProperty.addWindowListener(this);
		
		/********for warning of group name missing***************/
		groupNameMissing=new JDialog(dataGroupProperty,"Warning");
		groupNameMissing.setSize(300,100);
		groupNameMissing.setResizable(false);
		groupNameMissingOk=new JButton("ok");
		groupNameMissingOk.addActionListener(this);
		JLabel warn=new JLabel("You must specify a name for the group");
		JPanel no1=new JPanel(new FlowLayout(FlowLayout.CENTER));
		JPanel no2=new JPanel(new FlowLayout(FlowLayout.CENTER));
		no1.add(warn);
		no2.add(groupNameMissingOk);
		JPanel noPan=new JPanel();
		noPan.setLayout(new BorderLayout());
		noPan.add(no1,"Center");
		noPan.add(no2,"South");
		groupNameMissing.add(noPan);
		groupNameMissing.setLocation((d.width-300)/2,(d.height-100)/2);
		
		tabPan.addMouseListener(this);
		tabPan.addChangeListener(this);		
	}
	
	public void tryExit(){
//		System.out.println("trying to exit");
		boolean notSaved=false;
		for(Iterator<PolicyFrame> it=policies.iterator();it.hasNext();){
			if(it.next().changed){
				notSaved=true;
				break;
			}
		}
		if(notSaved){
			closeWindow.setVisible(true);
		}else{
			this.dispose();
			System.exit(0);
		}
	}
	
	public void saveFile(){
		//saves current project
		int selected=tabPan.getSelectedIndex();
		PolicyFrame pf=policies.get(selected);
		pf.validator.removeAll();
		File file;
		if(pf.getProjectName().equals("")){
			String filename=tabPan.getTitleAt(selected);
			if(pf.changed){
				filename=filename.substring(1);
			}
			File selectedFile=new File(filename);
			filechooserProj.setSelectedFile(selectedFile);
			filechooserProj.showSaveDialog(this);
			
			file=filechooserProj.getSelectedFile();
			if(file!=null){
//				System.out.println(file.getAbsolutePath());
				String s=file.getAbsolutePath();
				if(s.length()<8){
					s=s+".p3pproj";
				}else{
					String extension = s.substring(s.length()-8).toLowerCase();
					if(!extension.equals(".p3pproj")){
						s=s+".p3pproj";
					}
				}
				if(!s.equals(file.getAbsolutePath())){
					file=new File(s);
				}
				
				String fname=file.getName();
				fname=fname.substring(0,fname.length()-8);
				pf.setProjectName(fname);
				pf.setProjectPath(file.getAbsolutePath());
			}
		}else{
			file=new File(pf.projectPath);
		}
		
		try{
			if(file.exists()){
				file.delete();
			}
			file.createNewFile();
			
			FileOutputStream fo=new FileOutputStream(file);
			ObjectOutputStream so=new ObjectOutputStream(fo);
			
			pf.flushData();
			pf.changed=false;
			// this is needed, otherwise there will be exceptions on CellEditorRemover
			java.util.List<NutritionTableView> ts=pf.nutrition.tables;
			for(int i=0;i<ts.size();i++){
				if(ts.get(i).table.isEditing()){
					ts.get(i).table.getCellEditor().stopCellEditing();
				}
			}
			so.writeObject(pf);
			so.flush();
			so.close();
			fo.close();
			tabPan.setTitleAt(tabPan.getSelectedIndex(), pf.projectName);
			if(pf.tab.getSelectedIndex()==4){
				pf.validator.refresh();
			}
		}catch(Exception exception){
			System.out.println(exception);
		}
	}
	
	//clear the content of data group property dialog
	public void clearDataGroupDialog(){
		dataGroupName.setText("");
		indefinite.setSelected(true);
		dataGroupDescription.setText("");
		dataGroupIdentifiable.setSelected(false);
	}
	
	public void loadDataGroupDialog(){
		int i=tabPan.getSelectedIndex();
		NutritionTableView ntv=policies.get(i).nutrition.tables.get(dataGroupModify);
		dataGroupName.setText(ntv.getName());
		dataGroupDescription.setText(ntv.getDescription());
		int retention=ntv.getRetention();
		switch(retention){
		case NutritionTableView.RETENTION_BUSINESS:
			businessPractice.setSelected(true);
			break;
		case NutritionTableView.RETENTION_CURRENT:
			currentRequest.setSelected(true);
			break;
		case NutritionTableView.RETENTION_INDEFINITE:
			indefinite.setSelected(true);
			break;
		case NutritionTableView.RETENTION_LAW:
			applicableLaw.setSelected(true);
			break;
		case NutritionTableView.RETENTION_PURPOSE:
			statedPurpose.setSelected(true);
			break;
		default:
			break;
		}
		dataGroupIdentifiable.setSelected(ntv.isIdentifiable());
	}
	
	public void createNewDataGroup(){
		int i=tabPan.getSelectedIndex();
		policies.get(i).tab.setSelectedIndex(1);
		dataGroupModify=-1;
		
		tabPan.setEnabled(false);
		policies.get(i).tab.setEnabled(false);
		policies.get(i).nutrition.tab.setEnabled(false);
		clearDataGroupDialog();
		dataGroupProperty.setVisible(true);
	}
	
	public void contentChanged(){
		int index=tabPan.getSelectedIndex();
		PolicyFrame pf=policies.get(index);
		if(!pf.changed){
			pf.changed=true;
			String title=pf.projectName;
			if(title==""){
				title=MainFrame.getInstance().tabPan.getTitleAt(index);
			}
			title="*"+title;
			MainFrame.getInstance().tabPan.setTitleAt(index, title);
		}
	}
	/*---------action listener-----------------------*/
	@Override
	public void actionPerformed(ActionEvent e) {
		
		/*************close current tab********************/
		if(e.getSource().equals(closeTab) || e.getSource().equals(closeMenu)){
			int i=tabPan.getSelectedIndex();
			if(i>=0){
				if(!policies.get(i).changed){
					tabPan.remove(i);
					policies.remove(i);
					if(policies.size()==0){
						newFileCnt=1;
						PolicyFrame pf=new PolicyFrame();
						pf.config();
						policies.add(pf);
						tabPan.add("new project 1",pf.tab);
						newFileCnt=2;
					}
					int j=tabPan.getSelectedIndex();
					if(policies.get(j).nutrition.tables.size()>0){
						groupInfo.setEnabled(true);
						deleteGroup.setEnabled(true);
					}else{
						groupInfo.setEnabled(false);
						deleteGroup.setEnabled(false);
					}
				}else{
					//pop up a warning about unsaved work
					fileNotSaved.setVisible(true);
				}				
			}
		}
		//save file before close
		if(e.getSource().equals(fileNotSavedYes)){
			saveFile();
			int i=tabPan.getSelectedIndex();
			tabPan.remove(i);
			policies.remove(i);
			if(policies.size()==0){
				newFileCnt=1;
				PolicyFrame pf=new PolicyFrame();
				pf.config();
				policies.add(pf);
				tabPan.add("new project 1",pf.tab);
				newFileCnt=2;
			}
			int j=tabPan.getSelectedIndex();
			if(policies.get(j).nutrition.tables.size()>0){
				groupInfo.setEnabled(true);
				deleteGroup.setEnabled(true);
			}else{
				groupInfo.setEnabled(false);
				deleteGroup.setEnabled(false);
			}
			fileNotSaved.dispose();
		}
		//close without saving
		if(e.getSource().equals(fileNotSavedNo)){
			int i=tabPan.getSelectedIndex();
			tabPan.remove(i);
			policies.remove(i);
			if(policies.size()==0){
				newFileCnt=1;
				PolicyFrame pf=new PolicyFrame();
				pf.config();
				policies.add(pf);
				tabPan.add("new project 1",pf.tab);
				newFileCnt=2;
			}
			int j=tabPan.getSelectedIndex();
			if(policies.get(j).nutrition.tables.size()>0){
				groupInfo.setEnabled(true);
				deleteGroup.setEnabled(true);
			}else{
				groupInfo.setEnabled(false);
				deleteGroup.setEnabled(false);
			}
			fileNotSaved.dispose();
		}
		//cancel
		if(e.getSource().equals(fileNotSavedCancel)){
			fileNotSaved.dispose();
		}
		
		/**************create a new project*****************/
		if(e.getSource().equals(newMenu) || e.getSource().equals(newTab)){
			PolicyFrame pf=new PolicyFrame();

			pf.config();
			policies.add(pf);
			tabPan.add("new project "+newFileCnt,pf.tab);
			tabPan.setSelectedComponent(pf.tab);
			newFileCnt++;
		}
		
		/******************save project********************/
		if(e.getSource().equals(saveMenu) || e.getSource().equals(saveTab)){
			saveFile();
		}
		
		/******************save project********************/
		if(e.getSource().equals(saveAsMenu)){
			int selected=tabPan.getSelectedIndex();
			PolicyFrame pf=policies.get(selected);
			pf.validator.removeAll();
			File file;
			String filename;
			File selectedFile;
			if(pf.getProjectName().equals("")){
				filename=tabPan.getTitleAt(selected);
				if(pf.changed){
					filename=filename.substring(1);
				}
			}else{
				filename=pf.getProjectPath();
			}
				selectedFile=new File(filename);
				filechooserProj.setSelectedFile(selectedFile);
				filechooserProj.showSaveDialog(this);
				
				file=filechooserProj.getSelectedFile();
				if(file==null)
					return;

				String s=file.getAbsolutePath();
				if(s.length()<8){
					s=s+".p3pproj";
				}else{
					String extension = s.substring(s.length()-8).toLowerCase();
					if(!extension.equals(".p3pproj")){
						s=s+".p3pproj";
					}
				}
				if(!s.equals(file.getAbsolutePath())){
					file=new File(s);
				}
				
				String fname=file.getName();
				fname=fname.substring(0,fname.length()-8);
				pf.setProjectName(fname);
				pf.setProjectPath(file.getAbsolutePath());
			
//			System.out.println(fname);
			try{
				if(file.exists()){
					file.delete();
				}
				file.createNewFile();
				
				FileOutputStream fo=new FileOutputStream(file);
				ObjectOutputStream so=new ObjectOutputStream(fo);
				
				pf.flushData();
				pf.changed=false;

				// this is needed, otherwise there will be exceptions on CellEditorRemover
				java.util.List<NutritionTableView> ts=pf.nutrition.tables;
				for(int i=0;i<ts.size();i++){
					if(ts.get(i).table.isEditing()){
						ts.get(i).table.getCellEditor().stopCellEditing();
					}
				}
				so.writeObject(pf);
				so.flush();
				so.close();
				fo.close();
				tabPan.setTitleAt(tabPan.getSelectedIndex(), pf.projectName);
				if(pf.tab.getSelectedIndex()==4){
					pf.validator.refresh();
				}
			}catch(Exception exception){
				System.out.println(exception);
			}
		}
		/******************open project********************/
		if(e.getSource().equals(openMenu)){
			filechooserProj.setSelectedFile(null);
			filechooserProj.showOpenDialog(this);
			File file=filechooserProj.getSelectedFile();
			if(file!=null){
//				System.out.println(file.getAbsolutePath());
				String filepath=file.getAbsolutePath();
				boolean isOpen=false;
				if(policies.size()<=0){
					isOpen=false;
				}else{
					for(int i=0;i<policies.size();i++){
						PolicyFrame pf=policies.get(i);
						if(pf.projectPath.equals(filepath)){
							isOpen=true;
							tabPan.setSelectedIndex(i);
							break;
						}
					}
				}
				if(!isOpen){
					try{
						int index=tabPan.getSelectedIndex();
						String title=tabPan.getTitleAt(index);
						boolean change=policies.get(index).changed;
						
						FileInputStream fi=new FileInputStream(file);
						ObjectInputStream oi=new ObjectInputStream(fi);
						PolicyFrame pf=new PolicyFrame();
						pf.config();											
						PolicyFrame openPolicy=(PolicyFrame)oi.readObject();
						
						pf.copyData(openPolicy);	
						pf.projectPath=filepath;
						pf.tab.setSelectedIndex(0);
						pf.property.tab.setSelectedIndex(0);						
						pf.flushUI();
						policies.add(pf);
						tabPan.add(openPolicy.getProjectName(),pf.tab);
						tabPan.setSelectedComponent(pf.tab);
						oi.close();
						
						policies.get(index).changed=change;
						tabPan.setTitleAt(index, title);
						//tabPan.repaint();
					}catch(Exception exception){
						System.out.println(exception);
					}
				}
			}
		}
		/******************exit program********************/
		if(e.getSource().equals(exitMenu)){
			tryExit();
		}
		/**************don't exit program******************/
		if(e.getSource().equals(closeStay)){
			closeWindow.dispose();
		}
		/***************** exit anyway ********************/
		if(e.getSource().equals(closeClose)){
			this.dispose();
			System.exit(0);
		}
		//--------!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!-------//
		if(e.getSource().equals(newGroup)){
			createNewDataGroup();
//			System.out.println("newGroup");
		}
		
		if(e.getSource().equals(groupInfo)){
			int i=tabPan.getSelectedIndex();
			policies.get(i).tab.setSelectedIndex(1);
			dataGroupModify=policies.get(i).nutrition.tab.getSelectedIndex();
			tabPan.setEnabled(false);
			policies.get(i).tab.setEnabled(false);
			policies.get(i).nutrition.tab.setEnabled(false);
			loadDataGroupDialog();
			dataGroupProperty.setVisible(true);
//			System.out.println("groupInfo");
		}
		
		if(e.getSource().equals(deleteGroup)){
			int i=tabPan.getSelectedIndex();
			policies.get(i).tab.setSelectedIndex(1);
			dataGroupModify=policies.get(i).nutrition.tab.getSelectedIndex();
			policies.get(i).nutrition.delGroup(dataGroupModify);
			contentChanged();
//			System.out.println("deleteGroup");
			if(policies.get(i).nutrition.tables.size()<=0){
				groupInfo.setEnabled(false);
				deleteGroup.setEnabled(false);
			}
		}
		if(e.getSource().equals(dataGroupOk)){
			if(dataGroupName.getText().replaceAll(" ", "").equals("")){
				groupNameMissing.setVisible(true);
			}else{
				String name=dataGroupName.getText();
				String description=dataGroupDescription.getText();
				int retention=4;
				if(currentRequest.isSelected()){
					retention=NutritionTableView.RETENTION_CURRENT;
				}
				if(statedPurpose.isSelected()){
					retention=NutritionTableView.RETENTION_PURPOSE;
				}
				if(applicableLaw.isSelected()){
					retention=NutritionTableView.RETENTION_LAW;
				}
				if(businessPractice.isSelected()){
					retention=NutritionTableView.RETENTION_BUSINESS;
				}
				if(indefinite.isSelected()){
					retention=NutritionTableView.RETENTION_INDEFINITE;
				}
				boolean identifiable=dataGroupIdentifiable.isSelected();
				int i=tabPan.getSelectedIndex();
				if(dataGroupModify<0){
					//create new datagroup
					policies.get(i).nutrition.addGroup(name, retention, description, identifiable);
					contentChanged();
				}else{
					//modify current datagroup
					policies.get(i).nutrition.setGroupInfo(dataGroupModify, name, retention, description, identifiable);
					contentChanged();
				}
				
				groupInfo.setEnabled(true);
				deleteGroup.setEnabled(true);
				
				policies.get(i).tab.setSelectedIndex(1);

				policies.get(i).tab.setEnabled(true);
				policies.get(i).nutrition.tab.setEnabled(true);
				tabPan.setEnabled(true);
				dataGroupProperty.dispose();
			}
		}
		if(e.getSource().equals(dataGroupCancel)){
			int i=tabPan.getSelectedIndex();
			policies.get(i).tab.setEnabled(true);
			policies.get(i).nutrition.tab.setEnabled(true);
			tabPan.setEnabled(true);
			dataGroupProperty.dispose();
		}
		if(e.getSource().equals(groupNameMissingOk)){
			groupNameMissing.dispose();
		}
		
	}

	/*---------mouse listener-----------------------*/
	@Override
	public void mouseClicked(MouseEvent e) {
		
		if(e.getSource().equals(tabPan)){
			/***********deals with right click on tab***********/
			if(e.getButton()==MouseEvent.BUTTON3){
				pMenuTab.show(e.getComponent(),e.getX(),e.getY());
			}
		}
	}

	@Override
	public void mouseEntered(MouseEvent e) {
	}

	@Override
	public void mouseExited(MouseEvent e) {
	}

	@Override
	public void mousePressed(MouseEvent e) {
	}

	@Override
	public void mouseReleased(MouseEvent e) {
	}

	/*---------window listener-----------------------*/
	@Override
	public void windowActivated(WindowEvent e) {
	}

	@Override
	public void windowClosed(WindowEvent e) {
	}

	@Override
	public void windowClosing(WindowEvent e) {
		if(e.getSource().equals(this)){
			tryExit();
		}else{
			if(e.getSource().equals(dataGroupProperty)){
				int i=tabPan.getSelectedIndex();
				policies.get(i).tab.setEnabled(true);
				policies.get(i).nutrition.tab.setEnabled(true);
				tabPan.setEnabled(true);
				dataGroupProperty.dispose();
			}
		}
	}

	@Override
	public void windowDeactivated(WindowEvent e) {	
	}

	@Override
	public void windowDeiconified(WindowEvent e) {
	}

	@Override
	public void windowIconified(WindowEvent e) {	
	}

	@Override
	public void windowOpened(WindowEvent e) {	
	}

	@Override
	public void stateChanged(ChangeEvent e) {
		if(e.getSource().equals(tabPan)){
			int i=tabPan.getSelectedIndex();
			if(i>=0 && i<policies.size()){
				if(policies.get(i).nutrition.tables.size()>0){
					groupInfo.setEnabled(true);
					deleteGroup.setEnabled(true);
				}else{
					groupInfo.setEnabled(false);
					deleteGroup.setEnabled(false);
				}
			}
		}
		
	}
}
